package com.oauth2.config.service;

import com.oauth2.domain.TbPermission;
import com.oauth2.domain.TbUser;
import com.oauth2.domain.vo.MyUser;
import com.oauth2.service.TbPermissionService;
import com.oauth2.service.TbUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private TbUserService tbUserService;
    @Autowired
    private TbPermissionService tbPermissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        TbUser user = tbUserService.selectOneByUser(username);
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        if (user == null) {
            throw new UsernameNotFoundException("No user found with username: " + username);
        }
        // 获取用户授权
        List<TbPermission> tbPermissions = tbPermissionService.selectByUserId(user.getId());
        // 声明用户授权
        tbPermissions.forEach(tbPermission -> {
            if (tbPermission != null && tbPermission.getEnname() != null) {
                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(tbPermission.getEnname());
                grantedAuthorities.add(grantedAuthority);
            }
        });
        return new MyUser(String.valueOf(user.getId()), user.getUsername(), user.getPassword(), grantedAuthorities);
    }
}
